# server.py
# 从wsgiref模块导入:
from wsgiref.simple_server import make_server
# from cgi import parse_qs, escape
from urllib.parse import parse_qs
from html import escape
import json


# 导入我们自己编写的application函数:
def application(environ, start_response):
    # print(environ)
    # Returns a dictionary containing lists as values.
    d = parse_qs(environ['QUERY_STRING'])
    print(d.get('key', []))
    print(d.get('value', []))
    # Always escape user input to avoid script injection
    print(escape(d.get('value', ['0'])[0]))

    # In this idiom you must issue a list containing a default value.
    age = d.get('age', [''])[0]  # Returns the first age value.
    hobbies = d.get('hobbies', [])  # Returns a list of hobbies.
    # start_response('200 OK', [('Content-Type', 'text/html')])
    start_response('200 OK', [('Content-Type', 'application/json')])
    body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
    data = {'position': (0, 0)}
    body = json.dumps(data)
    return [body.encode('utf-8')]


# 创建一个服务器，IP地址为空，端口是8000，处理函数是application:
httpd = make_server('', 8000, application)
print('Serving HTTP on port 8000...')
import threading


def loop():
    import os
    print(os.system('C:\\Users\\panpan\\Anaconda2\\envs\\CNN_Test\\python ' + 'main.py'))


def loop2():
    import os
    print(os.system('C:\\Users\\panpan\\Anaconda2\\envs\\CNN_Test\\python ' + 'opencv_test.py'))


t = threading.Thread(target=loop, name='UIThread')
#t.start()
t2 = threading.Thread(target=loop2, name='UIThread2')
#t2.start()
# 开始监听HTTP请求:
httpd.serve_forever()
print('over')
